package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.all.util.Page;
import com.atguigu.gmall.list.client.ListFeignClient;
import com.atguigu.gmall.model.list.SearchParam;
import com.atguigu.gmall.model.list.SearchResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;

@Controller
public class ListController {
    @Autowired
    private ListFeignClient listFeignClient;

    /**
     * 搜索页面
     * @return
     **/
    @GetMapping(value = "/list")
    public String list(SearchParam searchParam,
                       @RequestParam Map<String, String> searchData,
                       Model model){
        //远程调用搜索
        SearchResponseVo search = listFeignClient.search(searchParam, searchData);
        //设置页面的数据
        model.addAttribute("goodsList",search.getGoodsList());
        model.addAttribute("trademarkList",search.getTrademarkList());
        model.addAttribute("attrsList",search.getAttrsList());
        model.addAttribute("searchData",searchData);
        Long total = search.getTotal();
        Integer pageNo = search.getPageNo();
        Integer pageSize = search.getPageSize();
        Page<Object> page = new Page<>(total,pageNo,pageSize);
        model.addAttribute("page",page);
        //获取当前的url
        String url = getUrl(searchData);
        model.addAttribute("url",url);
        //返回页面
        return "list/list";

    }

    /**
     * 获取当前的url
     * @param searchData
     * @return
     */
    private String getUrl(Map<String, String> searchData){
        String url = "/list?";
        for (Map.Entry<String, String> entry : searchData.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!key.equals("order")){
                url += key + "=" + value + "&";
            }

        }

        return url.substring(0,url.length()-1);
    }
}
